<?php

/*
 * 我的好友相关
 */

namespace Home\Controller;

class MyfriendController extends BaseMemberController {

    function _initialize() {
        parent::_initialize();
        $this->_user_id = session('visitor.user_id');
        $this->_friend_mod = M('friend');
    }

    /**
     * @api {get} /index.php?m=Home&c=Myfriend&a=friend_list 获取好友列表
     * @apiName 获取好友列表  
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 获取好友列表
     * 
     * 
     * @apiSuccess {String} user_name 用户名
     * @apiSuccess {String} portrait 用户头像
     * @apiSuccess {String} add_time 添加时间
     */
    function friend_list() {
        $map['owner_id'] = $this->_user_id;
        $friend_list = $this->_friend_mod
                ->field('f.*,m.user_name,m.portrait')
                ->alias('f')
                ->join('LEFT JOIN ' . C('DB_PREFIX') . 'member m ON m.user_id = f.friend_id')
                ->where($map)
                ->order('add_time desc')
                ->select();
        render('10000', '', array('friend_list' => $friend_list));
    }

    /**
     * @api {post} /index.php?m=Home&c=Myfriend&a=friend_add 新增好友
     * @apiName 获取好友列表  
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 获取好友列表
     * 
     * @apiParam {String} user_name 用户名/手机/邮箱
     * 
     */
    function friend_add() {
        $user_name = I('post.user_name', '');
        if (empty($user_name)) {
            render('10200', '用户名不能为空');
        }

        //查看当前用户名是否存在
        $member_mod = M('member');
        $member = $member_mod->where("user_name='{$user_name}' or phone_mob='{$user_name}' or email='{$user_name}'")->find();

        if (empty($member)) {
            render('10200', '当前用户不存在');
        }
		
        if ($member['user_id'] == $this->_user_id) {
            render('10200', '不能添加自己为好友');
        }

        //查看此好友是否被添加
        $map['owner_id'] = $this->_user_id;
        $map['friend_id'] = $member['user_id'];
        $friend = $this->_friend_mod->where($map)->find();
        if ($friend) {
            render('10200', '此用户已是你的好友');
        } else {
            $map['add_time'] = time();
            $this->_friend_mod->add($map);
            render('10000', '添加好友成功');
        }
    }

    /**
     * @api {get} /index.php?m=Home&c=Myfriend&a=friend_del 删除好友
     * @apiName 删除好友  
     * @apiGroup All
     * @apiVersion 0.1.0 
     * @apiDescription 删除好友
     * 
     * @apiParam {String} friend_id 好友ID
     */
    function friend_del() {
        $friend_id = I('request.friend_id', 0, 'intval');
        if (empty($friend_id)) {
            render('10200', '违规操作');
        }
        $map['friend_id'] = $friend_id;
        $map['owner_id'] = $this->_user_id;

        $result = $this->_friend_mod->where($map)->delete();
        if($result){
            render('10000', '删除好友成功');
        }else{
            render('19999', '删除好友失败');
        }
    }
    
    

}